package com.cht.commonUtil.mp;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cht.commonUtil.webInit.SP;
import com.cht.commonUtil.widgets.Widgets;

public class UpdateEmpRole extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding( SP.UIcodeSet );
		response.setContentType("application/json");
		response.setCharacterEncoding( SP.UIcodeSet );
		
		String subsysId = request.getParameter("subsysId");
		int roleId = Integer.parseInt( request.getParameter("roleId") );
		String empId = request.getParameter("empId");					
		String creatorId = request.getParameter("creatorId");			//進行這次異動的當事人
		String addOrDelete = request.getParameter("addOrDelete");
		int systemId = Integer.parseInt( request.getParameter("systemId") );
		int polyType = Integer.parseInt( request.getParameter("polyType") );
		String envId = "";
		String sql = "";
		String res = "";
		
		Connection conn = null;
		PreparedStatement ps = null;
		
		try {
			conn = Widgets.getConn();
			
			if ( "add".equalsIgnoreCase( addOrDelete ) ) {
				if ( polyType==1 ) {
					sql = "INSERT INTO mpemprolesubsys (subsysId,roleId,empId,sysSN,creatorId,cDT) VALUES (?,?,?,?,?,?)";	
				} else {
					envId = request.getParameter("envId");
					sql = "INSERT INTO mpemprolesubsysenv (subsysId,roleId,empId,sysSN,creatorId,cDT,envId) VALUES (?,?,?,?,?,?,?)";
				}
				
			} else {
				if ( polyType==1 ) {
					sql = "DELETE FROM mpemprolesubsys WHERE subsysId=? AND roleId=? AND empId=? AND sysSN=?";	
				} else {
					envId = request.getParameter("envId");
					sql = "DELETE FROM mpemprolesubsysenv WHERE subsysId=? AND roleId=? AND empId=? AND sysSN=? AND envId=?";
				}
			}
			ps = conn.prepareStatement(sql);
			ps.setString(1, subsysId);
			ps.setInt(2, roleId);
			ps.setString(3, empId);
			ps.setInt(4, systemId);
			if ( "add".equalsIgnoreCase( addOrDelete ) ) {
				ps.setString(5, creatorId);
				ps.setTimestamp(6, Widgets.cDT());
				if ( polyType!=1 ) {
					ps.setString(7, envId);
				}
			} else {
				if ( polyType!=1 ) {
					ps.setString(5, envId);
				}
			}
			ps.execute();
		} catch (Exception e) {
			res = Widgets.errLog(e);
		} finally {
			try {
				if ( ps !=null ) {ps.close();}
				if ( conn !=null ) {conn.close();}	
			} catch (Exception e) { e.printStackTrace(); };
			
		}
		response.getWriter().write(res);
	}

}
